const {passwordDecode} = require("../utils/passwordUtil");

const {toLine,getUrlParamNative} = require("../utils/utils");

const Controller = require('egg').Controller;
const lodash=require('lodash')

class MockController extends Controller {
    parseToken(str) {
        return passwordDecode(str)
    }

    getPassword(str){
        // [2].split('=')[1]
      var array1=  decodeURIComponent(str).split('&')
        var index1=array1.findIndex(item=>item.indexOf("password")>=0)
        return array1[index1].split("=")[1]
    }
    getMysql(token) {
        var str= this.parseToken(token)
        var host=decodeURIComponent(getUrlParamNative(str,'host'))
        var database=decodeURIComponent(getUrlParamNative(str,'database'))
        var password=this.getPassword(str)
        var user=decodeURIComponent(getUrlParamNative(str,'user'))
        var port=getUrlParamNative(str,'port')
        if (!database) {
            throw "请先mock登录系统之后再操作"
        }
        const knex = require('knex')({
            client: 'mysql',
            connection: {
                host, database, password, user, port
            }
        });
        return knex;
    }

    async page() {
        var tableName = this.ctx.params.tablename
        //拿到token
        var query = this.ctx.query;
        var body = this.ctx.request.body;
        var token = query.token || body.token||this.ctx.get('token');;
        var pageNum=query.pageNum||0
        var pageSize=query.pageSize||10
        pageNum=(pageNum)*pageSize;
        delete query.token
        delete body.token
        delete query.pageNum
        delete query.pageSize
        var mysql = await this.getMysql(token);
        var _queryObj={}
        lodash.map(query,(value,key)=>{
            if(value){
                _queryObj[key]=decodeURIComponent(value)
            }
        })
        console.log("查询参数",toLine(tableName),JSON.stringify(_queryObj))
        var result = await mysql.table(toLine(tableName)).select("*").where({
            ..._queryObj
        }).limit(pageSize).offset(pageNum)
        //   this.ctx.body = 'Hello world';
        this.ctx.body = result
    }
    async list() {
        var tableName = this.ctx.params.tablename
        //拿到token
        var query = this.ctx.query;
        var body = this.ctx.request.body;
        var token = query.token || body.token||this.ctx.get('token');;
        var pageNum=query.pageNum||0
        var pageSize=query.pageSize||10
        pageNum=(pageNum)*pageSize;
        delete query.token
        delete body.token
        delete query.pageNum
        delete query.pageSize
        var mysql = await this.getMysql(token);
        var _queryObj={}
        lodash.map(query,(value,key)=>{
            if(value){
                _queryObj[key]=decodeURIComponent(value)
            }
        })
        console.log("查询参数",toLine(tableName),JSON.stringify(_queryObj))
        var result = await mysql.table(toLine(tableName)).select("*").where({
            ..._queryObj
        }).limit(pageSize).offset(pageNum)
        //   this.ctx.body = 'Hello world';
        this.ctx.body = result
    }

    async add() {
        var tableName = this.ctx.params.tablename
        //拿到token
        var query = this.ctx.query;
        var body = this.ctx.request.body;
        var token = query.token || body.token||this.ctx.get('token');;
        delete query.token
        delete body.token
        var mysql = await this.getMysql(token);
        var _queryObj={}
        lodash.map(query,(value,key)=>{
            if(value){
                _queryObj[key]=decodeURIComponent(value)
            }
        })
        var _bodyObject={}
        lodash.map(body,(value,key)=>{
            if(value){
                _bodyObject[key]=decodeURIComponent(value)
            }
        })
        console.log("插入参数",toLine(tableName),JSON.stringify(_bodyObject))
        var result = await mysql.table(toLine(tableName)).insert(_bodyObject)
        //   this.ctx.body = 'Hello world';
        this.ctx.body = result
    }
    async update() {

        var tableName = this.ctx.params.tablename

        //拿到token
        var query = this.ctx.query;
        var body = this.ctx.request.body;
        var token = query.token || body.token||this.ctx.get('token');;
        delete query.token
        delete body.token
        var mysql = await this.getMysql(token);
        var tableKeyResult= await mysql.raw(`SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE table_name='${tableName}' AND constraint_name='PRIMARY'`)
        var tableKey=tableKeyResult[0][0].column_name||'id'
        var _queryObj={}
        lodash.map(query,(value,key)=>{
            if(value){
                _queryObj[key]=decodeURIComponent(value)
            }
        })
        var _bodyObject={}
        lodash.map(body,(value,key)=>{
            if(value){
                _bodyObject[key]=decodeURIComponent(value)
            }
        })
        console.log("插入参数",toLine(tableName),JSON.stringify(_bodyObject))
        var queryParams={..._queryObj}
        delete _bodyObject[tableKey]
        var result = await mysql.table(toLine(tableName)).where(queryParams).update(_bodyObject)
        //   this.ctx.body = 'Hello world';
        this.ctx.body = result
    }
}

module.exports = MockController;